package com.net.TCP04.char2;

import java.io.*;
import java.net.Socket;

/**
 * 发送数据线程
 *
 * @author jiangbang
 * @date 2016/8/11
 */
public class Send implements Runnable{
    //控制台输入流
    private BufferedReader console;
    //管道的输出流
    private DataOutputStream dos;
    //控制运行
    private boolean isRunning = true;

    public Send(){
        console = new BufferedReader(new InputStreamReader(System.in));
    }

    public Send(Socket client){
        this();
        try {
            dos = new DataOutputStream(client.getOutputStream());
        } catch (IOException e) {
            isRunning = false; //出异常 停止线程
            CloseUtil.ColseAll(dos,console);
        }
    }

    /**
     * 1从控制台接收数据
     * 2.发送数据
     */
    public void send(){
        String msg = getMsgFromConsole();
        if(null!=msg && msg.equals("")){
            try {
                dos.writeUTF(msg);
                dos.flush();//强制刷新
            } catch (IOException e) {
                isRunning = false; //出异常 停止线程
                CloseUtil.ColseAll(dos,console);
            }
        }

    }
    //1.从控制台接收数据
    private String getMsgFromConsole(){
        try {
            return console.readLine();
        } catch (IOException e) {
        }
        return "";
    }


    @Override
    public void run() {
        while(isRunning){
            send();
        }
    }


}
